<template>
  <div class="main-container" v-loading="isLoading">
    <DeviceSearchBar />
    <el-scrollbar class="config-container">
      <el-table :data="deviceStore.currentConfigs" style="width: 100%">
        <el-table-column fixed prop="ipAddress" label="IpAddress" />
        <el-table-column prop="port" label="Port" />
        <el-table-column prop="deviceName" label="DeviceName" />
        <el-table-column prop="deviceType" label="DeviceType" />
        <el-table-column prop="slot" label="Slot" />
        <el-table-column prop="rack" label="Rack" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button class="mt-4" style="width: 100%" @click="onOpenAddItemDialog">
        添加配置
      </el-button>
    </el-scrollbar>
    <el-dialog
      v-model="showAddItemDialog"
      title="添加新设备配置"
      width="400"
      :close-on-click-modal="false"
      draggable
    >
      <DeviceConfigItem
        style="margin: 10px"
        v-model:deviceName="newDeviceConfig.deviceName"
        v-model:port="newDeviceConfig.port"
        v-model:deviceType="newDeviceConfig.deviceType"
        v-model:ipAddress="newDeviceConfig.ipAddress"
        v-model:slot="newDeviceConfig.slot"
        v-model:rack="newDeviceConfig.rack"
      ></DeviceConfigItem>
      <div style="display: flex; justify-content: center; margin-top: 20px">
        <el-button type="primary" @click="onAddNewItem()">添加</el-button>
      </div>
    </el-dialog>
    <el-button type="danger" style="width: 100%; margin-top: 10px" @click="onUploadToDevice">
      配置下发设备
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useDeviceManagerStore } from '@/stores/device/manager'
import DeviceSearchBar from '@/components/device/device-search-bar.vue'
import DeviceConfigItem from '@/components/device/device-config-item.vue'
import type { DeviceConfig } from '@/types/device'
import { DeviceTyeps } from '@/types/device'
import { ElMessage } from 'element-plus'
import { ShowDeleteMessageBoxAsync, ShowWarningMessageBoxAsync } from '@/utils/message-box'
import { DeviceServerClient } from '@/api/axios/device-server-client'

const client = new DeviceServerClient(import.meta.env.VITE_DEVICE_SERVER_BASE_URL)
const isLoading = ref(false)
const deviceStore = useDeviceManagerStore()
const showAddItemDialog = ref(false)
let newDeviceConfig = ref<DeviceConfig>({
  id: '',
  deviceName: '',
  port: null,
  deviceType: DeviceTyeps.SiemensS1500,
  ipAddress: '',
  slot: 0,
  rack: 0
})

// 配置下发设备
async function onUploadToDevice() {
  if (
    !(await ShowWarningMessageBoxAsync(
      '配置下发设备将会修改远程设备的配置，请仔细检查您的配置是否完全正确？'
    ))
  ) {
    return
  }

  if (deviceStore.currentNodeId == '' || deviceStore.currentNodeId == null) {
    ElMessage.error('请选择设备 ID ！')
  } else if (deviceStore.currentNode == null) {
    ElMessage.error('请选查询指定的设备 ID ！')
  } else if (!deviceStore.hasConfig) {
    ElMessage.error('该设备 ID 没有任何配置！')
  } else {
    isLoading.value = true
    let result = await client.configAsync({
      deviceId: deviceStore.currentNodeId,
      task: {
        deviceConfigs: deviceStore.currentConfigs
      }
    })

    isLoading.value = false
    if (result.isSuccess) {
      ElMessage.success('配置下发设备成功！')
    } else {
      ElMessage.error(result.message)
    }
  }
}

async function deleteRow(index: number) {
  if (!(await ShowDeleteMessageBoxAsync())) {
    return
  }

  let config = deviceStore.currentConfigs[index]
  let result = await client.deleteDeviceConfigAsync(config.id || '')
  if (result.isSuccess) {
    // 删除设备配置
    deviceStore.removeConfigFromCurrentNode(index)
    ElMessage.success('删除配置成功！')
  } else {
    ElMessage.error(result.message)
  }
}

const onOpenAddItemDialog = () => {
  if (deviceStore.currentNode == null) {
    ElMessage.info('请先查询指定的设备 ID ！')
    return
  }
  showAddItemDialog.value = true
}

async function onAddNewItem() {
  let deviceConfigItem = newDeviceConfig.value
  var reg = new RegExp('^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$')

  if (deviceConfigItem.deviceName.length < 6) {
    ElMessage.error('设备逻辑名长度不能低于6个字符！')
  } else if (reg.test(deviceConfigItem.ipAddress) == false) {
    ElMessage.error('IP 地址格式不正确！')
  } else if (
    deviceConfigItem.port == null ||
    deviceConfigItem.port < 1 ||
    deviceConfigItem.port > 65535
  ) {
    ElMessage.error('IP 端口无效（0~65535）！')
  } else {
    try {
      let result = await client.insertDeviceConfigAsync({
        nodeId: deviceStore.currentNodeId,
        ...deviceConfigItem
      })

      if (result.isSuccess) {
        // 添加一个新的设备配置
        deviceStore.addConfigToCurrentNode(deviceConfigItem)
        // 重新初始化对象
        newDeviceConfig.value = {
          id: null,
          deviceName: '',
          port: null,
          deviceType: DeviceTyeps.SiemensS1500,
          ipAddress: '',
          slot: 0,
          rack: 0
        }
        ElMessage.success('成功添加新配置！')
      } else {
        ElMessage.error(result.message)
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('添加配置时出现未知错误！')
    }
    // 关闭弹窗
    showAddItemDialog.value = false
  }
}
</script>

<style scoped>
.main-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.config-container {
  height: 100%;
  padding: 20px 30px 20px;
  background-color: #fff;
  border: 1px solid #ddd;
  margin-top: 10px;
  border-radius: 5px;
}

.collapse-title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
</style>
